﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Shuba.Model;
using DynamicComparer;

namespace Shuba.Web.bulk_upload
{
    public partial class alternate_um_list : basePage
    {
        string msg = "";
        bool IsView, IsAdd, IsEdit, IsDelete, IsChecker;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Form.DefaultFocus = txtSearch.ClientID;
            this.Form.DefaultButton = btnSearch.UniqueID;

            string acl = GetUserAccess("ALTERNATE_UM");
            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);

            if (!IsView)
            {
                msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitSort();
                BindData();

                LabelTitle.Text = GetPageTitle("ALTERNATE_UM");

                if (IsAdd)
                {
                    btnAdd.Enabled = true;
                    btnUpload.Enabled = true;
                }
                else
                {
                    btnAdd.Enabled = false;
                    btnUpload.Enabled = false;
                }
            }
        }

        private void BindData()
        {
            Shuba.Business.AlternateUM BI = new Shuba.Business.AlternateUM();
            List<AlternateUMInfo > list;

            list = BI.GetList(txtSearch.Text);

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<AlternateUMInfo> comparer = new DynamicComparer<AlternateUMInfo>(sort);
                list.Sort(comparer);
            }
            gvList.DataSource = list;
            gvList.DataBind();

            if (IsDelete || IsEdit) gvList.Columns[gvList.Columns.Count - 1].Visible = true;
            else gvList.Columns[gvList.Columns.Count - 1].Visible = false;

            //FOR APPROVAL GRID
            if (IsChecker)
            {
                BindApprovalData();
                if (ApprovalGrid.Rows.Count > 0) { ApprovalPnl.Visible = true; } else { ApprovalPnl.Visible = false; }
            }
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;
            BindData();
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btnDelete = (LinkButton)e.Row.FindControl("btnDelete");
                LinkButton btnEdit = (LinkButton)e.Row.FindControl("btnEdit");

                if (IsEdit) btnEdit.Enabled = true; else btnEdit.Enabled = false;

                if (IsDelete && e.Row.Cells[gvList.Columns.Count - 2].Text == "1")
                {
                    btnDelete.Enabled = true;
                }
                else
                {
                    btnDelete.Enabled = false;
                    btnDelete.OnClientClick = "";
                }

                if (e.Row.Cells[e.Row.Cells.Count - 2].Text == "" || e.Row.Cells[e.Row.Cells.Count - 2].Text == "1")
                {
                    e.Row.Cells[e.Row.Cells.Count - 2].Text = "Active";

                    e.Row.Font.Bold = false;
                    e.Row.ForeColor = System.Drawing.Color.Black;
                }
                else
                {
                    //untuk alternate jika inactive maka tidak bisa diedit dan didelete
                    btnEdit.Enabled = false;
                    btnDelete.Enabled = false;

                    e.Row.Cells[e.Row.Cells.Count - 2].Text = "Inactive";

                    e.Row.Font.Bold = true;
                    e.Row.ForeColor = System.Drawing.Color.Red;

                    e.Row.Cells[e.Row.Cells.Count - 1].ForeColor = System.Drawing.Color.Black;
                    e.Row.Cells[e.Row.Cells.Count - 1].Font.Bold = false;
                }
            }
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remove" || e.CommandName == "Edit")
            {
                GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

                //string[] ParamID = e.CommandArgument.ToString().Split('~');
                string BranchID = gvList.DataKeys[row.RowIndex]["BRANCH_ID"] == null ? "" : gvList.DataKeys[row.RowIndex]["BRANCH_ID"].ToString();
                string NIP = gvList.DataKeys[row.RowIndex]["NIP"] == null ? "" : gvList.DataKeys[row.RowIndex]["NIP"].ToString();
                string ALTERNATE_FOR = gvList.DataKeys[row.RowIndex]["ALTERNATE_FOR"] == null ? "" : gvList.DataKeys[row.RowIndex]["ALTERNATE_FOR"].ToString();
                DateTime EFF_FROM = Convert.ToDateTime(gvList.DataKeys[row.RowIndex]["EFF_DATE_FROM"]);
                DateTime EFF_TO = Convert.ToDateTime(gvList.DataKeys[row.RowIndex]["EFF_DATE_TO"]);

                if (e.CommandName == "Remove")
                {
                    Shuba.Business.AlternateUM BI = new Shuba.Business.AlternateUM();
                    AlternateUMInfo BIInfo = BI.Get(BranchID, NIP);

                    BIInfo.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                    BIInfo.UPDATE_DATE = ProcessingDate();
                    BIInfo.ACT_TYPE = "DELETE";
                    BIInfo.BRANCH_ID_ORIG = BranchID;
                    BIInfo.NIP_ORIG = NIP;
                    BIInfo.ALTERNATE_FOR_ORIG = ALTERNATE_FOR;
                    BIInfo.EFF_DATE_FROM_ORIG = EFF_FROM;
                    BIInfo.EFF_DATE_TO_ORIG = EFF_TO;

                    try
                    {
                        BI.Save(BIInfo);
                        AddLog("DELETE", "DELETE BRANCH NIP SO MAPPING");
                    }
                    catch (Exception ex)
                    {
                        msg = ex.Message.ToString();
                        ErrBox.Visible = true;
                        ErrMsg.Text = msg;
                    }

                    if (msg == "") BindData();// RestartPage();
                }
                else
                {
                    Response.Redirect("alternate_um_add.aspx?a=ed&id=" + e.CommandArgument);
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        /*======================================
               APPROVAL GRID START HERE
        =======================================
        */
        private void BindApprovalData()
        {
            Shuba.Business.AlternateUM BI = new Shuba.Business.AlternateUM();
            List<AlternateUMInfo> list;

            list = BI.GetListApproval(HttpContext.Current.User.Identity.Name);
            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<AlternateUMInfo> comparer = new DynamicComparer<AlternateUMInfo>(sort);
                list.Sort(comparer);
            }
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();
        }

        protected void ApprovalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[2].Text.Trim() == "&nbsp;" || e.Row.Cells[5].Text.Trim() == "&nbsp;" || e.Row.Cells[6].Text.Trim() == "&nbsp;")
                {
                    e.Row.Font.Bold = true;
                    e.Row.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    e.Row.Font.Bold = false;
                    e.Row.ForeColor = System.Drawing.Color.Black;
                }
            }
        }

        protected void ApprovalGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;
            BindApprovalData();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            //bool IsValidData = false;
            int ErrorCount = 0, SuccessCount = 0;
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                if (chkItemSelect.Checked)
                {
                    if (row.ForeColor != System.Drawing.Color.Red)
                    {
                        //IsValidData = true;

                        string NIP = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                        string BRANCH_ID = ApprovalGrid.DataKeys[row.RowIndex].Values["BRANCH_ID"].ToString();
                        string ActType = ApprovalGrid.DataKeys[row.RowIndex].Values["ACT_TYPE"].ToString();
                        string ALTERNATE_FOR = ApprovalGrid.DataKeys[row.RowIndex].Values["ALTERNATE_FOR"].ToString();
                        DateTime EFF_FROM = Convert.ToDateTime(ApprovalGrid.DataKeys[row.RowIndex].Values["EFF_DATE_FROM"]);
                        DateTime EFF_TO = Convert.ToDateTime(ApprovalGrid.DataKeys[row.RowIndex].Values["EFF_DATE_TO"]);

                        if (Approve(BRANCH_ID, NIP, ALTERNATE_FOR, EFF_FROM, EFF_TO, ActType, true) > 0)
                        {
                            SuccessCount++;
                        }
                        else ErrorCount++;
                    }
                    else
                    {
                        ErrorCount++;
                    }
                }
            }

            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nSuccessfully Approve : " + SuccessCount + " Record(s)\\n\\nFailed to Approve : " + ErrorCount + " Record(s)";
                if (ErrorCount > 0) msg += "\\n\\nPlease make sure:\\n- NIP is correct and already registered in Console Management \\n- Unit Code is correct";
                BindData();
                Alert(msg);
            }
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                if (chkItemSelect.Checked)
                {
                    string NIP = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                    string BRANCH_ID = ApprovalGrid.DataKeys[row.RowIndex].Values["BRANCH_ID"].ToString();
                    string ActType = ApprovalGrid.DataKeys[row.RowIndex].Values["ACT_TYPE"].ToString();
                    string ALTERNATE_FOR = ApprovalGrid.DataKeys[row.RowIndex].Values["ALTERNATE_FOR"].ToString();
                    DateTime EFF_FROM = Convert.ToDateTime(ApprovalGrid.DataKeys[row.RowIndex].Values["EFF_DATE_FROM"]);
                    DateTime EFF_TO = Convert.ToDateTime(ApprovalGrid.DataKeys[row.RowIndex].Values["EFF_DATE_TO"]);

                    Approve(BRANCH_ID, NIP, ALTERNATE_FOR, EFF_FROM, EFF_TO, ActType, false);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "NoApprove").ToString();
            BindData();
            Alert(msg);
            //AlertAndRedirect(msg, Request.Url.PathAndQuery);
        }

        private int Approve(string BRANCH_ID, string NIP, string ALTERNATE_FOR, DateTime EFF_DATE_FROM, DateTime EFF_DATE_TO, string ActType, bool IsApprove)
        {
            int status = 0;
            Shuba.Business.AlternateUM BI = new Shuba.Business.AlternateUM();

            if (IsApprove)
            {
                try
                {
                    status = BI.Approve(BRANCH_ID, NIP, ALTERNATE_FOR, EFF_DATE_FROM, EFF_DATE_TO, ActType);
                    AddLog("APPROVAL", "APPROVE ALTERNATE UM");
                }
                catch (Exception ex)
                {
                    ErrBox.Visible = true;
                    ErrMsg.Text = ex.Message;
                }
            }
            else
            {
                AddLog("APPROVAL", "REJECT ALTERNATE UM");
                status = BI.Reject(BRANCH_ID, NIP, ALTERNATE_FOR, EFF_DATE_FROM, EFF_DATE_TO);
            }
            return status;
        }

        protected void btnApproveAll_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            Shuba.Business.AlternateUM BI = new Shuba.Business.AlternateUM();
            List<AlternateUMInfo> list = BI.GetListApproval(HttpContext.Current.User.Identity.Name);

            foreach (AlternateUMInfo item in list)
            {
                try
                {
                    if (Approve(item.BRANCH_ID, item.NIP, item.ALTERNATE_FOR, item.EFF_DATE_FROM, item.EFF_DATE_TO, item.ACT_TYPE, true) > 0) SuccessCount++;
                    else ErrorCount++;
                }
                catch (Exception)
                {
                    ErrorCount++;
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nTotal record to approve : " + list.Count + "Record(s)\\nSuccessfully Approve : " + SuccessCount + " Record(s)\\nFailed to Approve : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);
        }

        protected void btnRejectAll_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            Shuba.Business.AlternateUM BI = new Shuba.Business.AlternateUM();
            List<AlternateUMInfo> list = BI.GetListApproval(HttpContext.Current.User.Identity.Name);

            foreach (AlternateUMInfo item in list)
            {
                try
                {
                    if (Approve(item.BRANCH_ID, item.NIP, item.ALTERNATE_FOR, item.EFF_DATE_FROM, item.EFF_DATE_TO, item.ACT_TYPE, false) > 0) SuccessCount++;
                    else ErrorCount++;
                }
                catch (Exception)
                {
                    ErrorCount++;
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nTotal record to reject : " + list.Count + "Record(s)\\nSuccessfully Reject : " + SuccessCount + " Record(s)\\nFailed to Reject : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);
        }
    }
}
